<template>
	<view>
		<view class="grid-box u-m-b-30">
			<view v-if="chooseLocation.address" class="u-flex">
				<view class="u-flex-1">
					<view class="u-p-b-10"><text class="u-font-32">{{chooseLocation.name}}</text></view>
					<view><text class="u-tips-color u-font-24">{{chooseLocation.address}}</text></view>
				</view>
				<u-button type="warning" :plain="true" @click="showmap = true" size="mini">
					<text class="u-p-r-10">修改地址</text>
					<u-icon name="arrow-right"></u-icon>
				</u-button>
			</view>
			<u-button v-else type="warning" :plain="true" @click="showmap = true">
				<text class="u-p-r-10">选择地址</text>
				<u-icon name="arrow-right"></u-icon>
			</u-button>
		</view>
		<view class="grid-box">
			<u-form :model="form" :rules="rules" ref="uForm" label-width="180">
				<u-form-item label="站点名称" prop="name" required >
					<u-input v-model="form.name" :border="true" placeholder="请填写站点名称" />
				</u-form-item>
				<u-form-item label="所属加盟商" prop="franchiseid" required >
					<u-input v-model="selectFranchise" type="select" :border="true" @click="franchiseShow = true" />
					<franchiseList v-model="franchiseShow" @confirm="getSelectFranchise"></franchiseList>
				</u-form-item>
				<u-form-item label="所在地区" prop="cityid" required >
					<u-input v-model="selectArea" type="select" :border="true" @click="cityshow = true" />
				</u-form-item>
				<u-form-item label="详细地址" prop="address" required >
					<u-input v-model="form.address" :border="true" type="textarea" placeholder="详细地址"/>
				</u-form-item>
				<u-form-item label="营业时间" prop="servicetime" required >
					<u-input v-model="form.servicetime" :border="true" placeholder="请填写营业时间" />
				</u-form-item>
				<u-form-item label="联系号码" required >
					<u-input v-model="form.telephone" :border="true"/>
				</u-form-item>
				<u-form-item label="上传封面" >
					<common-upload max-count="1" @on-success="uploadSuccess" @on-remove="removePhoto"></common-upload>
				</u-form-item>
			</u-form>
		</view>
		<!-- 底部按钮 -->
		<view class="bottom-box">
			<view class="fixed-container">
				<view class="btn-group">
					<view class="u-flex">
						<view class="u-p-r-30" @click="back"><text style="text-decoration: underline;">返回</text></view>
						<view class="u-flex-1" v-if="id > 0"><u-button type="primary" @click="submit">保存修改</u-button></view>
						<view class="u-flex-1" v-else><u-button type="primary" @click="submit">确定新建</u-button></view>
					</view>
				</view>
			</view>
			<view class="fixed-placeholder"></view>
		</view>
		<!-- 选择所在地区 -->
		<citypicker ref="citypicker" :show="cityshow" :level="4" @select="getSelectCity" @close="cityshow = false"></citypicker>
	</view>
</template>

<script>
	import franchiseList from '@/components/form-select-type/franchise-list.vue'
	import {
		mapState
	} from 'vuex';
	export default {
		components:{
			franchiseList
		},
		data() {
			return {
				id: 0,
				form: {
					cityid: 0,//地区Id
					address: "",//详细地址
					lat: 23.625349,//纬度
					lng: 113.042648,//经度
					name: "",//名称
					telephone: "",//电话
					icon: "",//图标
					franchiseid: 0,//加盟商
					servicetime: "",//营业时间
					isGrantIntegral: true,//站点回收是否发放积分
				},
				rules: {},
				piclist: [],
				fileUploadURL: getApp().globalData.fileUploadURL,
				// 选择地区
				cityshow: false,
				selectArea: '',
				// 选择加盟商
				franchiseShow: false,
				selectFranchise: '',
				// 选择定位
				showmap: false,
				chooseLocation:{
					name: '',
					address: '',
					latitude: 0,
					longitude: 0
				}
			}
		},
		computed: {
			...mapState({
				header: state => state.Authorization
			})
		},
		watch:{
			showmap(val){
				console.log('点击展示地图')
				if(val){
					this.showmap = false
					uni.chooseLocation({
						success: (res)=> {
							console.log('位置名称：' + res.name);
							console.log('详细地址：' + res.address);
							console.log('纬度：' + res.latitude);
							console.log('经度：' + res.longitude);
							this.chooseLocation = res
							
							this.form.address = res.name
							this.form.lat = res.latitude
							this.form.lng = res.longitude
						}
					})
				}
			}
		},
		onLoad(opt) {
			this.id = opt.id
			if(this.id){
				this.getStoreDetails()
			}
		},
		methods: {
			// 自定义验证方法
			validateForm() {
				const errors = [];

				// 验证必填字段
				if (!this.form.name) {
					errors.push('请输入站点名称');
				}

				if (!this.form.franchiseid || this.form.franchiseid === 0) {
					errors.push('请选择所属加盟商');
				}

				if (!this.form.cityid || this.form.cityid === 0) {
					errors.push('请选择所在地区');
				}

				if (!this.form.address) {
					errors.push('请输入详细地址');
				}

				if (!this.form.servicetime) {
					errors.push('请输入营业时间');
				}

				// // 验证手机号格式（如果填写了电话）
				// if (this.form.telephone && !/^1[3-9]\d{9}$/.test(this.form.telephone)) {
				// 	errors.push('请输入正确的手机号码');
				// }
				
				if (!this.form.telephone) {
					errors.push('请输入联系号码');
				}

				return errors;
			},
			getStoreDetails(){
				this.$u.get('/Store/Details?id='+this.id).then((res)=>{
					this.form = {
						...res,
						cityid: res.address.cityid,
						address: res.address.address,//详细地址
						lat: res.address.lat,
						lng: res.address.lng,
					}
					this.selectFranchise = res.franchisename
					this.selectArea = res.address.citynames.replace(/,/g,"-")
					
					this.chooseLocation = {
						name: res.address.address,
						address: res.address.citynames.replace(/,/g,"-"),
						latitude: res.address.lat,
						longitude: res.address.lng
					}
					
					this.piclist = [
						{
							url: this.fileURL + res.icon,
						}
					]
				})
			},
			// 表单提交方法
			submit() {
				// 使用自定义验证方法
				const errors = this.validateForm();
				
				if (errors.length > 0) {
					// 显示错误信息
					uni.showToast({
						title: errors[0], // 显示第一个错误
						icon: 'none'
					});
					return;
				}
				
				// 验证通过，执行提交操作
				this.submitType(this.id, this.form);
			},
			submitType(storeId,form) {
				let api = ''
				if (storeId > 0) {
					api = '/Store/Edit'
				}else{
					api = '/Store/create'
				}
				
				uni.showLoading({
					title: '提交中...'
				})
				this.$u.post(api, form).then((res) => {
					uni.showToast({
						title: '提交成功'
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			getSelectCity(arr) { //城市选择回调函数
				console.log(arr)
				this.cityshow = false
				// this.selectArea = '';
				let cityidArr = [];
				let getArr = arr.filter(n => n.id != 0)
				let areaname = '';
				getArr.forEach((item, index) => {
					if (index == getArr.length - 1) {
						areaname += item.name
					} else {
						areaname += item.name + '-'
					}
					cityidArr.push(item.id);
				});
				if (cityidArr.length > 0)
					// this.form.cityid = cityidArr.join(',');
					this.form.cityid = cityidArr[cityidArr.length - 1];
				if (areaname)
					this.selectArea = areaname;
			},
			// 选择加盟商
			getSelectFranchise(obj){
				console.log('getSelectFranchise',obj)
				this.franchiseShow = false
				this.form.franchiseid = obj.id
				this.selectFranchise = obj.name
			},
			// 上传拍照
			uploadSuccess(data, index, lists, name) {
				this.form.icon = data.datas.path
			},
			removePhoto(index, lists, name) {
				this.piclist.splice(index, 1)
				// console.log(this.fileList)
			},
			// 上传图片失败时处理
			uploadError(data, index, lists, name) {
				uni.showToast({
					icon: 'none',
					title: '提交失败，请重试'
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.bottom-box {
		.fixed-container {
			position: fixed;
			bottom: 0;
			background-color: #fff;
			width: 750rpx;
			padding-top: 0;
			height: 132rpx;
			z-index: 99;
			box-shadow: 0 0 16rpx #e7e7e7;
		}
	
		.fixed-placeholder {
			height: 132rpx;
			width: 750rpx;
			margin-top: 30rpx;
		}
	
		.total {
			line-height: 80rpx;
			padding-left: 30rpx;
			padding-right: 30rpx;
			margin: 0;
		}
	
		.btn-group {
			padding: 30rpx;
	
			.u-flex-1+.u-flex-1 {
				margin-left: 20rpx;
			}
		}
	}
</style>